//
//  AppViewController.swift
//  QualityControlSystem
//
//  Created by Daniel Hu on 12/26/16.
//  Copyright © 2016 com.mask. All rights reserved.
//

import UIKit

class AppViewController: UIViewController {
    
    // MARK: - Properties
    
    var tabVC: UITabBarController?
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    // MARK: - Life cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(userDidLogedIn), name: .userDidLogedin, object: nil)
        SettingManager.applyDefaultSetting()
    }
    
    static func initialAppViewControllerFromDefaultStoryBoard() -> AppViewController {
        return UIStoryboard(name: "AppViewController", bundle: nil).instantiateInitialViewController() as! AppViewController
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        presentLoginControllerIfNeeded(withCompletion: {(_ didLogedin: Bool) -> Void in
            loadMainUI()
        })
    }
    
    // MARK: - Setup main user interface
    
    func launchApp(in window: UIWindow) {
        window.rootViewController = self
        window.makeKeyAndVisible()
    }
    
    func loadMainUI() {
        if tabVC != nil {
            return
        }
        
        tabVC = UIStoryboard(name: "CommonLoginSystem", bundle: nil).instantiateInitialViewController() as? UITabBarController
        
        if let tabVC = self.tabVC {
            addChildViewController(tabVC)
            view.addSubview(tabVC.view)
            tabVC.didMove(toParentViewController: self)
        }
    }
    
    // MARK: - Login view controller
    
    func presentLoginControllerIfNeeded(withCompletion completion: (_ didLogedin: Bool) -> Void) {
        if shouldPresentLoginController() {
            let loginVC = LoginViewController()
            present(loginVC, animated: false, completion: { _ in })
        }
        else {
            completion(false)
        }
    }
    
    func shouldPresentLoginController() -> Bool {
        return (User.shared.token == nil) ? true : false
    }
    
    // MARK: - Event response
    
    func userDidLogedIn() {
        loadMainUI()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
